<template>
  <div class="xtx-pagination">
    <a href="javascript:;" :class="{disabled:active===1}" @click="pageTurner(-1)">上一页</a>
    <span v-show="pager.start!==1">...</span>
    <a
      href="javascript:;"
      :class="{ active: active === item }"
      @click="active=item"
      v-for="(item, index) in pager.btnCrr"
      :key="index"
      >{{ item }}</a
    >
    <span  v-show="pager.end!==pager.count">...</span>
    <a href="javascript:;" :class="{disabled:active===pager.count}" @click="pageTurner(1)">下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    // 总条数
    total: {
      type: Number,
      required: true
    },
    // 按钮个数
    btn: {
      type: Number,
      default: 5
    },
    // 开始页码
    currentPage: {
      type: Number,
      default: 1
    }
  },
  setup (props, { emit }) {
    const pageSize = ref(10)
    const active = ref(1)
    watch(props, () => {
      active.value = props.currentPage
    }, { immediate: true })
    const pager = computed(() => {
      const count = Math.ceil(props.total / pageSize.value)
      const offset = Math.floor(props.btn / 2)
      let start = active.value - offset
      let end = active.value + offset
      if (start < 1) {
        start = 1
        end = props.btn
      }
      if (end > count) {
        end = count
        start = end - props.btn + 1
      }
      if (count < props.btn) {
        start = 1
        end = count
      }
      const btnCrr = []
      for (let i = start; i <= end; i++) {
        btnCrr.push(i)
      }
      return {
        start,
        end,
        btnCrr,
        count,
        offset
      }
    })
    const pageTurner = (valeu) => {
      if (active.value + valeu < 1 || active.value + valeu > pager.value.count) return
      active.value += valeu
    }
    watch(active, () => {
      emit('pageTurner', active.value)
    })
    return { pager, active, pageTurner }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333;
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
